﻿using System.Collections;
using UnityEngine;

public class WWWLoader : ZLoader
{
    public override float Progress
    {
        get
        {
            float prog = !IsLoading ? 0 : Www.progress;
            return IsLoaded ? 1 : prog;
        }
    }

    public WWWLoader(string url, string key, string resPath = "")
    {
        Request = new RequestInfo(url, key, resPath);
    }

    public override IEnumerator Load()
    {
        Www = new WWW(Request.url);
        IsLoading = true;
        yield return Www;
    }

    public override void Update()
    {
        if (IsLoading)
        {
            if (LastProgress != Www.progress)
            {
                LastProgress = Www.progress;
                BroadEvent(new EventArg(ConstData.CHANGE));
            }
            if (!string.IsNullOrEmpty(Www.error))
            {
                IsLoading = false; IsLoaded = true;
                BroadEvent(new EventArg(ConstData.ERROR));
            }
            else if (Www.isDone)
            {
                IsLoading = false; IsLoaded = true;
                BroadEvent(new EventArg(ConstData.COMPLETE));
            }
        }
    }

    public override void Clear()
    {
        Www = null;
        Request = null;
    }
}